﻿using System;
using System.Collections;
using BestHTTP;
using UnityEngine.Networking;

namespace Networking.Runtime
{
    public class SimpleUnityWebRequest
    {
        public Action<SimpleUnityWebRequest> OnRequestStateChanged;
        public bool IsDone => _unityWebRequest.isDone;
        public byte[] Data => _unityWebRequest.downloadHandler.data;
        private UnityWebRequest _unityWebRequest;
        public SimpleUnityWebRequest(string url)
        {
            _unityWebRequest = UnityWebRequest.Get(url);
        }

        public void Send()
        {
            _unityWebRequest.SendWebRequest();
            HTTPUpdateDelegator.CheckInstance();
            HTTPUpdateDelegator.Instance.StartCoroutine(SendRequest());
        }

        private IEnumerator SendRequest()
        {
            while (_unityWebRequest.isDone)
            {
                yield return _unityWebRequest;
            }

            if (_unityWebRequest.error!= null)
            {
                OnRequestStateChanged?.Invoke(this);
            }
            else
            {
                OnRequestStateChanged?.Invoke(this);
            }
        }
    }
}
